package com.idea.easy.log.publisher;

import com.idea.easy.log.provider.EasyLogInfoUtil;
import com.idea.easy.log.model.CustomLogModel;
import com.idea.easy.log.provider.SpringAware;
import com.idea.easy.log.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import javax.servlet.http.HttpServletRequest;

/**
 * @className: CustomLogPublisher
 * @description: 自定义日志事件发布者
 * @author: salad
 * @date: 2022/6/3
 **/
@Slf4j
public class CustomLogPublisher extends LogPublisher{


    private final String logLevel;

    private final String logId;

    private final String logData;

    public CustomLogPublisher(ApplicationEvent event,String logId,String logData,String logLevel) {
        this.logLevel = logLevel;
        this.logId = logId;
        this.logData = logData;
        setEvent(event);
    }

    public static CustomLogPublisher event(ApplicationEvent event,String logId,String logData,String logLevel){
        return new CustomLogPublisher(event,logId,logData,logLevel);
    }


    @Override
    public void publish() {
        HttpServletRequest request = WebUtil.getRequest();
        ApplicationEvent event = getEvent();
        CustomLogModel model = (CustomLogModel) event.getSource();
        model.setLogId(logId)
                .setLogData(logData)
                .setLogLevel(logLevel);
        Thread thread = Thread.currentThread();
        StackTraceElement[] trace = thread.getStackTrace();
        if (trace.length > 3) {
            model.setMethodClass(trace[3].getClassName());
            model.setMethodName(trace[3].getMethodName());
        }else{
            model.setMethodClass("unknown");
            model.setMethodName("unknown");
        }
        EasyLogInfoUtil.appendRequestInfo(request,model);
        SpringAware.publishEvent(event);
    }

}
